//
//  SIStatusListViewModel.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/2.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import Foundation
import SDWebImage
//MARK: -上拉刷新最大尝试次数,如果超出次数,直接返回,access-Token的接收次数有限,大量数据处理时候也有这个请求
private let maxPullupTryTimes = 3

class SIStatusListViewModel {
    
    lazy var statusList = [SIStatusViewModel]()
    
    ///上拉刷新第几次出错
    private var pullupErrorTime = 0
    
    /// 处理网络数据
    ///
    /// - parameter pullup:     是否上拉刷新
    /// - parameter completion: 完成回调
    func loadStatus(pullup: Bool, completion: (isSuccess: Bool, shouldRefresh: Bool) -> ()) {
        
        if pullup && pullupErrorTime > maxPullupTryTimes {
            
            completion(isSuccess: true, shouldRefresh: false)
            
            return
            
        }
        
        let since_id = pullup ? 0 : (statusList.first?.status.id ?? 0)
        let max_id = !pullup ? 0 : (statusList.last?.status.id ?? 0)
        
         SIStatusListDAL.loadStatus(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            
            var array = [SIStatusViewModel]()
            
            for dict in list ?? [] {
                
                guard let model = SIStatus.yy_model(with: dict) else {
                    continue
                }
                
                array.append(SIStatusViewModel(model: model))
                
            }
            
            //MARK: 根据是否上拉决定拼接数据的顺序
            if pullup {
                
                self.statusList += array
            } else {
                
                self.statusList = array + self.statusList
            }
            
            ///判断上拉刷新出错的次数
            if pullup && array.count == 0 {
                
                self.pullupErrorTime += 1
                
                completion(isSuccess: isSuccess, shouldRefresh: false)
                
            } else {
                
                ///缓存单张图片
                self.cacheSingleImage(list: array, completion: completion)
                
                ///网络数据加载完成回调
//                completion(isSuccess: isSuccess, shouldRefresh: true)
                
            }
            
        }
    }
    
    ///缓存本次下载微博数据数组中的单张图像
    ///list: 本次下载的视图模型数组
    private func cacheSingleImage(list: [SIStatusViewModel], completion: (isSuccess: Bool, shouldRefresh: Bool) -> ()) {
        
        ///建立调度组
        let group = DispatchGroup()
        
        var length = 0
        
        for vm in list {
            
            if vm.picURLs?.count != 1 {
                
                continue
                
            }
            
            guard let pic = vm.picURLs?[0].thumbnail_pic,
                url = URL(string: pic) else {
                
                    continue
            }
            ///入组
            group.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                
                if let image = image,
                    data = UIImagePNGRepresentation(image) {
                    
                    length += data.count
                    
                    vm.updateSingleImageSize(image: image)
                    
                }
                
                ///在block或闭包的最后一行 出组
                group.leave()
            })
            
        }
        ///监听单张图片的缓存结束
        group.notify(queue: DispatchQueue.main) {
            
            print("缓存完成 大小\(length / 1024)K")
            
            ///网络数据加载完成回调
            completion(isSuccess: true, shouldRefresh: true)
        }
    }
    
}
